import { t } from 'i18next'
import React, { useState, useEffect, useRef } from 'react'
import { Modal, Message, InnerInputRef } from '@kedacom/react-next'
import { Poll, SelectItem } from '../interface'
import { Alert, confirmModal } from '@/components/Alert'
import { useTvWallStore } from '../store'
import { useRequest } from 'ahooks'
import {
	fetchAddTvWallPlan,
	fetchChangeTVWallPlan,
	fetchDelTVWallPlan,
	fetchGetStylesByMeetingMoidStyleInfo,
	fetchGetTvWallPlanList,
	fetchTVWallPlanDetail,
	fetchUpdateTVWallPlan,
} from '@/api/manager/tvwall'
import { PlanDetailEntity, StyleDetail, TvWallMemberItemEntity } from '@/api/manager/tvwall/interface'
import { revert_poll } from '@/api/manager/poll/interface'
import { useMccStore } from '@/pages/manager/store'
import shallow from 'zustand/shallow'
import { useLockStore } from '@/store/globalLock'
export default function useService({
	getPollParam,
	testPollParam,
}: {
	getPollParam: () => Poll | null
	testPollParam: () => boolean
}) {
	const { meetingMoid, updateData, is_batch_poll, getMccTVWallsByMeetingMoid, correct_style, mode, preName } =
		useTvWallStore((state) => ({
			meetingMoid: state.meetingMoid,
			data: state.data,
			updateData: state.updateData,
			is_batch_poll: state.is_batch_poll,
			correct_style: state.correct_style,
			getMccTVWallsByMeetingMoid: state.getMccTVWallsByMeetingMoid,
			mode: state.mode,
			preName: state.preName,
		}))
	const { meetingType } = useMccStore(
		(state) => ({
			meetingType: state.mccInfo.meetingType,
		}),
		shallow
	)
	const { lock, isLock, unLock } = useLockStore(
		(state) => ({
			lock: state.lock,
			isLock: state.isLock,
			unLock: state.unLock,
		}),
		shallow
	)
	const [planValue, setPlanValue] = useState('0') //预案id
	const [planOptions, setPlanOptions] = useState<SelectItem[]>([{ label: t('不使用预案'), value: '0' }]) //预案选项
	const [name, setName] = useState('') //预案名称
	const [isSavePlanOpen, setIsSavePlanOpen] = useState(false) //预案名称弹窗
	const inputRef = useRef<InnerInputRef>(null)
	/**加载电视墙预案 */
	const { data: tvwallPlanData, run } = useRequest(() => fetchGetTvWallPlanList(meetingMoid))
	useEffect(() => {
		if (tvwallPlanData && tvwallPlanData.success) {
			let arr = tvwallPlanData.data
				? tvwallPlanData.data.map((item) => ({ label: item.name, value: item.id }))
				: []
			arr.unshift({ label: t('不使用预案'), value: '0' })
			setPlanOptions(arr)
		}
	}, [tvwallPlanData])
	/**变更名称或者预案信息列表更新选中值 */
	useEffect(() => {
		setPlanValue(planOptions.find((item) => item.label === preName)?.value ?? '0')
	}, [preName, planOptions])
	/**载入预案*/
	/**如果是空预案 请求改变通道预案请求
	 * 非空预案直接改变通道请求
	 */
	const changePollDTO = (poll: any) => {
		if (poll && JSON.stringify(poll) != '{}') {
			return Object.assign({}, poll, {
				members: poll.members
					? poll.members.map((item: any) => {
							if (item) {
								return Object.assign({}, item, { mt_id: item.mt_id || item.mtid || item.mt_key })
							}
							return null
					  })
					: [],
			})
		}
		return null
	}
	const changeVmpDTO = (vmp: any) => {
		if (vmp && JSON.stringify(vmp) != '{}') {
			return Object.assign({}, vmp, {
				members: vmp.members
					? vmp.members.map((item: any) => {
							if (item) {
								return Object.assign({}, item, {
									mt_id: item.mt_id || item.mtid || item.mt_key,
									poll: changePollDTO(item.poll),
								})
							}
							return null
					  })
					: null,
				poll: changePollDTO(vmp.poll),
			})
		}
		return null
	}
	const changeSpiltDTO = (spilt: any) => {
		return spilt
			? spilt.map((item: any) => {
					if (item) {
						return Object.assign({}, item, {
							mt_id: item.mt_id || item.mtid || item.mt_key,
						})
					}
					return null
			  })
			: null
	}
	const changeTvwallMemberDTO = (item: TvWallMemberItemEntity) => {
		return Object.assign({}, item, {
			mt_id: item.mt_id || item.mtid || item.mt_key,
			poll: changePollDTO(item.poll),
			vmp: changeVmpDTO(item.vmp),
			spilt: changeSpiltDTO(item.spilt),
		})
	}
	const changeTvwallMemberDTOArr = (arr: TvWallMemberItemEntity[] | undefined) => {
		return arr ? arr.map(changeTvwallMemberDTO) : []
	}
	/**检测预案能否切换*/
	const testPlanDataIsCanChangePlan = (para: Pick<PlanDetailEntity, 'id' | 'name' | 'tvwalls'>): boolean => {
		var flag = false
		for (let i = 0; i < para.tvwalls.length; i++) {
			if (para.tvwalls[i].mode === 1) {
				let _members = para.tvwalls[i].members
				flag =
					_members?.some((item) => {
						return (
							(meetingType === 1 && item.member_type === 9) ||
							(meetingType !== 1 && item.member_type === 8)
						)
					}) ?? false
			}
			if (flag) {
				break
			}
		}
		return flag
	}
	const changePlan = async (id: string) => {
		if (is_batch_poll) {
			confirmModal({
				msg: t('选择预案将停止当前的批量轮询，确定选择预案？'),
				onOk: () => {
					if (id === '0') {
						/**切换空预案 */
						setPlanValue(id) /**将点击的预案选中 */
						handleChangeEmptyPlan()
					} else {
						let callback = (_data: PlanDetailEntity) => {
							if (_data.tvwalls) {
								_data.tvwalls = _data.tvwalls.map((item) => {
									return Object.assign({}, item, {
										members: item.mode === 1 ? changeTvwallMemberDTOArr(item.members) : null,
										batch_poll: item.mode === 2 ? changePollDTO(item.batch_poll) : null,
									})
								})
							}
							let flag = testPlanDataIsCanChangePlan(_data)
							if (flag) {
								Alert(t('当前预案不支持'))
								return
							}
							setPlanValue(id) /**将点击的预案选中 */
							let params = { id: _data.id, name: _data.name, tvwalls: _data.tvwalls }
							changeTVWallPlan(params)
						}
						getPlanById(id, callback)
					}
				},
			})
		} else {
			if (id === '0') {
				/**切换空预案 */
				setPlanValue(id) /**将点击的预案选中 */
				handleChangeEmptyPlan()
			} else {
				let callback = (_data: PlanDetailEntity) => {
					if (_data.tvwalls) {
						_data.tvwalls = _data.tvwalls.map((item) => {
							return Object.assign({}, item, {
								members: item.mode === 1 ? changeTvwallMemberDTOArr(item.members) : null,
								batch_poll: item.mode === 2 ? changePollDTO(item.batch_poll) : null,
							})
						})
					}
					let flag = testPlanDataIsCanChangePlan(_data)
					if (flag) {
						Alert('该预案不支持')
						return
					}
					setPlanValue(id) /**将点击的预案选中 */
					let params = { id: _data.id, name: _data.name, tvwalls: _data.tvwalls }
					changeTVWallPlan(params)
				}
				getPlanById(id, callback)
			}
		}
	}
	/**切换到空预案 */
	const handleChangeEmptyPlan = () => {
		var para = {
			id: '',
			name: '',
			tvwalls: [],
		}
		changeTVWallPlan && changeTVWallPlan(para)
	}
	/**获取预案详情*/
	const getPlanById = async (planId: string, callback: (response: PlanDetailEntity) => void) => {
		const res = await fetchTVWallPlanDetail(meetingMoid, planId)
		if (res.success) {
			callback(res)
		} else {
			Alert(res.description || '')
		}
	}
	/**保存预案前先获取当前的电视墙数据 */
	const getallStyleData = async (callback: (result: any) => void) => {
		const res = await fetchGetStylesByMeetingMoidStyleInfo(meetingMoid)
		if (res.success) {
			if (res.data && res.data?.styles && res.data?.styles.length === 0) {
				Alert(t('请选择风格'))
				return false
			}
			let _styles = res.data?.styles || []
			let _result = []
			for (let i = 0; i < _styles.length; i++) {
				const _style_id = _styles[i].style_id
				let _info: StyleDetail = _styles[i]
				if (mode === 2) {
					//批量轮询
					if (_style_id === correct_style) {
						let _flag = testPollParam()
						if (!_flag) return
						var para = getPollParam()
						if (para) {
							_info.batch_poll = Object.assign({}, _info.batch_poll, { ...revert_poll(para) })
						}
						_result.push(Object.assign(_info, { style_id: _style_id, members: [] }))
						break
					}
				} else {
					//定制，要移除 多流终端的 3个占位，保留有数据的第一个位置
					if (_info.members && _info.members.length > 0) {
						_info.members = deleteStreamInPlan(_info)
					}
					_result.push(Object.assign(_info, { style_id: _style_id }))
				}
			}
			if (callback) callback(_result)
		}
	}
	const deleteStreamInPlan = (list: Pick<StyleDetail, 'members'>) => {
		let _members = list.members
		let mtKey, mtchnid: any
		for (let i = 0; i < _members.length; i++) {
			let data = _members[i]
			if (data.member_type === 1 && data.stream === 1) {
				if (mtKey === data.mt_key && mtchnid < data.mt_chn_id) {
					_members[i] = {
						is_used: 0,
						is_mine: 0,
						mt_id: '',
						member_type: 1,
					} as TvWallMemberItemEntity
					continue
				}
				mtKey = data.mt_key
				mtchnid = data.mt_chn_id
			}
		}
		let result = list.members.filter((item) => {
			return item.member_type !== 0
		})
		return result
	}
	/**删除预案*/
	const deletePlan = (e: React.MouseEvent, item: { label: string; value: string }) => {
		e.stopPropagation()
		confirmModal({
			msg: t('是否确定删除{{name}}？', { name: item.label }),
			onOk: async () => {
				const res = await fetchDelTVWallPlan(meetingMoid, item.value)
				if (res.success) {
					let arr = planOptions.filter((i) => i.value !== item.value)
					setPlanOptions(arr)
					if (planValue === item.value) {
						setPlanValue('0')
						updateData(null)
					}
				} else {
					Alert(res.description || '')
				}
			},
		})
	}
	/**点击保存预案 */
	const savePlanClick = () => {
		if (planValue === '0') {
			setName('')
			setIsSavePlanOpen(true) /**关闭弹框 */
		} else {
			let _plan = planOptions.find((x) => x.value == planValue)
			let _name = _plan?.label || ''
			getallStyleData((result: any) => {
				updatePlan(_name, planValue, result)
			})
		}
	}
	/**保存预案 */
	const savePlan = async () => {
		getallStyleData(async (result: any) => {
			let valid = await inputRef.current?.valid()
			if (!valid) return
			var param = {
				tvwalls: result /**转换数据 */,
				name: name /**预案名称*/,
			}
			const res = await fetchAddTvWallPlan(meetingMoid, param)
			if (res.success) {
				setIsSavePlanOpen(false) /**关闭弹框 */
				const allPlanRes = await fetchGetTvWallPlanList(meetingMoid)
				if (allPlanRes && allPlanRes.success && allPlanRes.data) {
					let arr = allPlanRes.data.map((item) => ({ label: item.name, value: item.id }))
					arr.unshift({ label: t('不使用预案'), value: '0' })
					setPlanOptions(arr)
					// let plan = allPlanRes.data.find((x) => x.name === name)
					// if (plan) {
					// 	getPlanById(plan.id, function (plan) {
					// 		let params = { id: plan.id, name: plan.name, tvwalls: plan.tvwalls }
					// 		changeTVWallPlan(params)
					// 	})
					// }
				}
				Message.info(t('预案保存成功'))
			} else {
				Alert(res.description || t('预案保存失败'))
			}
		})
	}
	/**更新预案 */
	const updatePlan = async (_name: string, id: string, _result: any) => {
		var params = {
			tvwalls: _result, // 电视墙数据
			name: _name, // 预案名称
			id: id,
		}
		let lock_key = 'updatePlan:' + meetingMoid
		if (isLock(lock_key)) return
		lock(lock_key)
		const res = await fetchUpdateTVWallPlan(meetingMoid, id, params)
		unLock(lock_key)
		if (res.success) {
			run()
			Message.info(t('预案保存成功'))
		} else {
			Alert(res.description || t('预案保存失败'))
		}
	}
	/**发送预案改变请求*/
	const changeTVWallPlan = async (para: Pick<PlanDetailEntity, 'id' | 'name' | 'tvwalls'>) => {
		let lock_key = 'changeTVWallPlan:' + meetingMoid
		if (isLock(lock_key)) return
		lock(lock_key)
		const res = await fetchChangeTVWallPlan(meetingMoid, para)
		unLock(lock_key)
		if (res.success) {
			if (planValue !== '0') {
				Message.info(t('预案载入成功'))
			}
			setTimeout(function () {
				/**风格id */
				getMccTVWallsByMeetingMoid(meetingMoid)
			}, 1000)
		} else {
			Alert(res.description || t('操作失败'))
		}
	}
	return {
		inputRef,
		/** 预案选项 */
		planOptions,
		/** 预案选项值 */
		planValue,
		/** 载入预案 */
		changePlan,
		/** 删除预案 */
		deletePlan,
		/** 保存预案弹窗是否打开 */
		isSavePlanOpen,
		/** 保存预案弹窗是否打开方法 */
		setIsSavePlanOpen,
		/** 保存或修改预案 */
		savePlanClick,
		/** 保存新预案 */
		savePlan,
		/** 预案名 */
		name,
		/** 设置预案名 */
		setName,
	}
}
